package com.zf.shuashua.ui.popup;

import android.animation.ValueAnimator;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.zf.shuashua.R;

/**
 * 新客专享
 */
public class NewUserDialog extends Dialog {

    private ImageView imgReceive;
    private ImageView imgClose;
    private TextView tvNext;
    private String value;
    private OnPopupListener mListener;

    private ValueAnimator receiveAnim;

    public NewUserDialog(@NonNull Context context, String value) {
        super(context);
        this.value = value;
    }

    public void close() {
        dismiss();
    }

    public void setPopupListener(OnPopupListener listener) {
        this.mListener = listener;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_new_user);
        try {
            getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        } catch (Exception e) {

        }
        setCancelable(false);
        setCanceledOnTouchOutside(false);
        setupView();
    }

    private void setupView() {
        imgClose = findViewById(R.id.img_close);
        imgClose.setOnClickListener(v -> {
            dismiss();
            if (mListener != null) {
                mListener.onClose();
            }
        });
        tvNext = findViewById(R.id.tv_next);
        tvNext.setText(value);
        tvNext.setOnClickListener(v -> {
            dismiss();
            if (mListener != null) {
                mListener.onNext();
            }
        });

        imgReceive = findViewById(R.id.iv_receive);

        imgReceive.setOnClickListener(v -> {
            if (mListener != null) {
                mListener.onNext();
            }
            dismiss();
        });

    }

    @Override
    public void show() {
        super.show();
        if (receiveAnim != null && receiveAnim.isRunning()) {
            receiveAnim.end();
        }
        receiveAnim = ValueAnimator.ofFloat(0.9F, 1F);
        receiveAnim.setDuration(300);
        receiveAnim.setRepeatCount(-1);
        receiveAnim.setRepeatMode(ValueAnimator.REVERSE);
        receiveAnim.setInterpolator(new AccelerateDecelerateInterpolator());
        receiveAnim.addUpdateListener(animation -> {
            float value = (float) animation.getAnimatedValue();
            imgReceive.setScaleX(value);
            imgReceive.setScaleY(value);
        });
        receiveAnim.start();
    }

    @Override
    public void dismiss() {
        super.dismiss();
        if (receiveAnim != null && receiveAnim.isRunning()) {
            receiveAnim.end();
        }
    }
}

